<template>
  <div>
    <el-form :model="eventForm" :rules="eventFormRoles" ref="eventForm" label-width="10em">
      <h-box header="活动基本信息">
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="eventForm.title" placeholder="请输入活动标题，最多 16 个字" style="width: 400px;"></el-input>
          <div class="hui-color-text-secondary hui-font-size-small">活动标题不对消费者展示，仅供管理员备注用</div>
        </el-form-item>
        <el-form-item label="给用户打标签" prop="userTags">
          <hpro-select-tags :value.sync="eventForm.userTags" style="width: 400px;"></hpro-select-tags>
          <div class="hui-color-text-secondary hui-font-size-small">
            <span>给参加过活动的用户打标签，美味建议商户以标签管理参加过活动的用户。</span>
            <router-link to="/home/user/tags/list" target="_blank">新建标签</router-link>
          </div>
        </el-form-item>
        <el-form-item label="活动时间" prop="_dateRange">
          <h-date-range :value.sync="eventForm._dateRange" :start-time.sync="eventForm.startTime" :end-time.sync="eventForm.endTime" style="width: 400px;"></h-date-range>
        </el-form-item>
      </h-box>
      <h-box header="活动奖励">
        <el-form-item label="奖励规则" prop="level">
          <el-table :data="eventForm.level" stripe border style="width: 400px; line-height: 23px;">
            <el-table-column label="时间(分钟)" width="100px">
              <template slot-scope="scope">{{ scope.row.min }} - {{ scope.row.max }}</template>
            </el-table-column>
            <el-table-column label="赠送">
              <template slot-scope="scope">
                <div v-for="(item, index) in scope.row.reward" :key="index">{{ item.title }} × {{ item.number }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="90px">
              <template slot-scope="scope">
                <el-button @click="handleDeleteLevel(scope.row)" type="danger" size="mini" plain>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="hui-color-text-secondary hui-font-size-small">为保证消费者体验，最多添加 3 级奖励规则</div>
          <el-button @click="handleDialogLevelFormOpen" :disabled="eventForm.level.length >= 3" type="primary" size="mini" icon="el-icon-plus" plain>添加一个奖励规则</el-button>
        </el-form-item>
      </h-box>
      <h-box header="活动参与限制">
        <el-form-item label="活动门店限制" prop="eventAllBranch">
          <el-radio-group v-model="eventForm.eventAllBranch" @change="onChangeCanEventBranch">
            <el-radio :label="true">所有门店参加</el-radio>
            <el-radio :label="false">部分门店参加</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="参加活动门店" prop="canEventBranch" v-if="!eventForm.eventAllBranch">
          <el-table :data="eventForm.canEventBranch" border stripe size="medium" style="width: 400px; line-height: 23px;" class="hui-mb-1">
            <el-table-column label="门店ID" prop="id"></el-table-column>
            <el-table-column label="门店名称" prop="label"></el-table-column>
          </el-table>
          <el-button @click="handleDialogBranch" type="primary" size="small" icon="el-icon-location" plain>设置活动门店</el-button>
        </el-form-item>
      </h-box>
      <h-box>
        <el-form-item label="" slot="footer" class="hui-mb-0">
          <el-button @click="handleSubmit('eventForm')" :loading="loading" type="primary">{{ type === 'edit' ? '保存' : '创建' }}</el-button>
          <el-button @click="handleBack">返回</el-button>
        </el-form-item>
      </h-box>
    </el-form>

    <!-- 增加一级奖励模态框，start -->
    <el-dialog title="请填写奖励信息" :visible.sync="dialogVisibleLevelForm" width="700px">
      <el-form :model="levelForm" :rules="levelFormRoles" ref="levelForm" label-width="10em">
        <el-form-item label="等位时间(分钟)" required>
          <span class="hui-mr-8px">大于等于</span>
          <el-form-item prop="min" style="display: inline-block;">
            <el-input-number v-model="levelForm.min" :disabled="eventForm.level.length > 0" placeholder="请选择" :step="5" :min="0" style="width: 140px;" size="medium"></el-input-number>
          </el-form-item>
          <span class="hui-mx-8px">，小于</span>
          <el-form-item prop="max" style="display: inline-block;">
            <el-input-number v-model="levelForm.max" placeholder="请选择" :step="5" :min="0" style="width: 140px;" size="medium"></el-input-number>
          </el-form-item>
        </el-form-item>
        <el-form-item label="奖励类型" prop="type">
          <el-radio-group v-model="levelForm.type" @change="onChangeType">
            <el-radio label="coupon">送优惠券</el-radio>
            <el-radio label="lucky">送红包</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="奖励内容" prop="reward">
          <el-table :data="levelForm.reward" stripe border size="small" style="line-height: 23px;">
            <el-table-column label="优惠券/红包" prop="title"></el-table-column>
            <el-table-column label="数量" prop="number"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="handleDeleteReward(scope.$index, scope.row)" type="danger" size="mini" plain="">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="hui-color-text-secondary hui-font-size-small">美味建议，每级奖励以 1 个为宜，最多不超过 2 个</div>
          <el-button @click="handleDialogCoupon" v-if="levelForm.type === 'coupon'" :disabled="levelForm.reward.length > 1" type="primary" size="mini" icon="el-icon-plus" plain>添加优惠券</el-button>
          <el-button @click="handleDialogCoupon" v-else-if="levelForm.type === 'lucky'" :disabled="levelForm.reward.length > 1" type="success" size="mini" icon="el-icon-plus" plain>添加红包</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="hui-text-right">
        <el-button @click="handleDialogLevelFormClose">取 消</el-button>
        <el-button @click="handleSubmitReward('levelForm')" type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 增加一级奖励模态框，end -->

    <hpro-dialog-branch :visible.sync="dialogVisibleBranch" :value.sync="eventForm.canEventBranch"></hpro-dialog-branch>
    <hpro-dialog-reward :type="levelForm.type" number-ctrl :visible.sync="dialogVisibleReward" :value.sync="levelForm.reward"></hpro-dialog-reward>
  </div>
</template>

<script>
export default {
  data () {
    return {
      type: '',
      loading: false,
      dialogVisibleLevelForm: false,
      dialogVisibleReward: false,
      dialogVisibleBranch: false,
      eventForm: {
        title: '',
        userTags: [],
        _dateRange: [],
        startTime: '',
        endTime: '',
        level: [],
        eventAllBranch: true,
        canEventBranch: []
      },
      eventFormRoles: {
        title: [
          {
            required: true,
            message: '请输入活动标题',
            trigger: 'blur, change'
          },
          {
            max: 16,
            message: '活动标题最多 16 个字',
            trigger: 'blur, change'
          }
        ],
        userTags: [
          {
            type: 'array',
            max: 5,
            message: '可选标签不超过 5 个',
            trigger: 'blur, change'
          }
        ],
        _dateRange: [
          {
            required: true,
            type: 'array',
            len: 2,
            fields: {
              0: {
                required: true,
                type: 'integer',
                message: '活动时间必填',
                trigger: 'change'
              },
              1: {
                required: true,
                type: 'integer',
                message: '活动时间必填',
                trigger: 'change'
              }
            }
          }
        ],
        level: [
          {
            required: true,
            type: 'array',
            max: 3,
            message: '活动奖励 1 - 3 级',
            trigger: 'change'
          }
        ],
        eventAllBranch: [
          {
            required: true,
            type: 'boolean',
            message: '参加用户限制必选',
            trigger: 'change'
          }
        ],
        canEventBranch: [
          {
            required: true,
            type: 'array',
            message: '请至少选择 1 个可参与活动的会员卡',
            trigger: 'change'
          }
        ]
      },
      levelForm: {
        min: undefined,
        max: undefined,
        type: 'coupon',
        reward: []
      },
      levelFormRoles: {
        min: [
          {
            required: true,
            type: 'integer',
            min: 0,
            message: '请填写开始分钟，仅限整数',
            trigger: 'blur, change'
          }
        ],
        max: [
          {
            required: true,
            type: 'integer',
            min: 0,
            message: '请填写结束分钟，仅限整数',
            trigger: 'blur, change'
          }
        ],
        type: [
          {
            required: true,
            message: '奖励类型必选',
            trigger: 'change'
          }
        ],
        reward: [
          {
            required: true,
            type: 'array',
            message: '请至少选择 1 个优惠券或红包',
            trigger: 'change'
          }
        ]
      }
    }
  },
  created () {
    this.setType()
  },
  methods: {
    // 根据url判断类型
    setType () {
      let type = this.$route.query.type
      this.type = type
      if (type === 'edit') {
        this.initMockData()
      }
    },

    // 模拟数据
    initMockData () {
      let eventForm = this.eventForm
      let tmp = {
        title: '某门店的排队活动',
        userTags: [],
        _dateRange: [],
        startTime: 1519228800,
        endTime: 1524412799,
        level: [
          {
            min: 0,
            max: 30,
            type: 'coupon',
            reward: [
              {
                cardId: '1',
                title: '优惠券标题1',
                number: 1
              }
            ]
          },
          {
            min: 30,
            max: 120,
            type: 'coupon',
            reward: [
              {
                cardId: '2',
                title: '优惠券标题2',
                number: 1
              }
            ]
          }
        ],
        eventAllBranch: false,
        canEventBranch: [
          {
            id: '1',
            label: '门店名称1'
          }
        ]
      }
      tmp._dateRange.unshift(tmp.startTime * 1000)
      tmp._dateRange.push(tmp.endTime * 1000)
      eventForm = tmp
      this.eventForm = eventForm
    },

    // 删除已添加的奖励事件
    handleDeleteLevel (index, row) {
      let level = this.eventForm.level
      level.splice(index, 1)
      this.eventForm.level = level
    },

    // 打开新增等级模态框事件
    handleDialogLevelFormOpen () {
      let eventForm = this.eventForm
      let levelForm = this.levelForm
      let l = eventForm.level.length
      // 如果之前已经有一个级别，把上一个级别的结束当做新级别的开始，配合模版把input变成disabled，避免手工输入出现断档或者冲突
      if (eventForm.level.length > 0) {
        levelForm.min = eventForm.level[l - 1].max
      }
      this.dialogVisibleLevelForm = true
    },

    // 关闭新增等级模态框事件
    handleDialogLevelFormClose () {
      this.dialogVisibleLevelForm = false
      this.resetLevelForm()
    },

    // 重置levelForm
    resetLevelForm () {
      this.levelForm = {
        min: undefined,
        max: undefined,
        type: 'coupon',
        reward: []
      }
    },

    // 奖励类型变化事件
    onChangeType (val) {
      this.levelForm.reward = []
    },

    // 打开红包优惠券选择模态框
    handleDialogCoupon () {
      this.dialogVisibleReward = true
    },

    // 删除已选择的优惠券或红包事件
    handleDeleteReward (index, row) {
      let reward = this.levelForm.reward
      reward.splice(index, 1)
      this.levelForm.reward = reward
    },

    // 增加一个j奖励等级表单校验
    handleSubmitReward (formName) {
      let levelForm = this.levelForm
      let eventForm = this.eventForm
      // 结束时间需大于开始时间
      if (levelForm.max > levelForm.min) {
        this.$formSubmit(formName).then(() => {
          eventForm.level.push(levelForm)
          this.eventForm.level = eventForm.level
          this.handleDialogLevelFormClose()
        }).catch(() => {
          return false
        })
      } else {
        console.log('结束时间需大于开始时间！')
        this.$message({
          message: '结束时间需大于开始时间, 请检查!',
          type: 'warning'
        })
        return false
      }
    },

    // 设置参加活动门店为空
    onChangeCanEventBranch () {
      if (this.eventForm.eventAllBranch) {
        this.eventForm.canEventBranch = []
      }
    },

    // 打开选择门店模态框
    handleDialogBranch () {
      this.dialogVisibleBranch = true
    },

    // 返回
    handleBack () {
      this.$router.back()
    },

    // 表单校验
    handleSubmit (formName) {
      this.$formSubmit(formName).then(() => {
        console.log('表单校验成功，提交')
        this.$loading()
        this.loading = true
        setTimeout(() => {
          this.$message({
            message: '活动保存成功！',
            type: 'success'
          })
          this.handleBack()
          this.$loading().close()
        }, 1000)
      }).catch(() => {
        console.log('表单校验失败！')
        this.$message({
          message: '必要的活动信息没填写完整, 请检查!',
          type: 'warning'
        })
        this.loading = false
      })
    }
  }
}
</script>
